//
//  ComposeViewController.swift
//  个人微博
//
//  Created by 一介布衣 on 16/2/27.
//  Copyright © 2016年 HUAMANLOU. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setBottomToolBar()
        setPictrueSelector()
        
        // 注册通知
        registerNotification()
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }

    @objc private func keyBoardWillChange(notif:NSNotification) {
        print(notif)
        // 在动画闭包中修改底部的工具条的位置，更新底部约束
        // 1.获取动画运行的时间
        let duration = (notif.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 2.键盘结束的frame,CGRect是结构体，结构体需要转换为NSValue对象才能够添加到字典中
        let rect = (notif.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let height = screenHeight - rect.origin.y
        // 在动画闭包中更新约束
        UIView.animateWithDuration(duration) { () -> Void in
            // 更新工具条的约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(-height)
            })
            
            // 强制刷新页面
            self.view.layoutIfNeeded()
        }
        
    }
    
    // 移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    /// 发博微博
    @objc private func send() {
        let urlString = "2/statuses/update.json"
        let parameters = ["access_token":AccountViewModel.sharedAccountViewModel.access_token,"status":textView.text]
        
        if pictrueSelector.imageList.count > 0 {
//            let imageData = UIImagePNGRepresentation(pictrueSelector.imageList.first!)
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                // 将需要上传的文件转换为二进制的数据，拼接到formData中
//                formData.appendPartWithFileData(imageData!, name: "pic", fileName: "XXXXXXX", mimeType: "application/octet-stream")
                
                // 多张图片的上传
                var index = 0
                for image in self.pictrueSelector.imageList {
                    let data = UIImagePNGRepresentation(image)
                    formData.appendPartWithFileData(data!, name: "pic", fileName: "fileName\(index)", mimeType: "image/jpeg")
                    index++
                }
                
                
                }, progress: nil, success: { (_, result) -> Void in
//                    print(result)
                    SVProgressHUD.showSuccessWithStatus("微博发布成功")
                    self.close()
                    
                }, failure: { (_, error) -> Void in
                    print(error)
                    
            })
        }else {
            
            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                
                if error != nil {
                    // 发布微博失败
                    SVProgressHUD.showErrorWithStatus("发布微博失败，请检查网络")
                    return
                }
                
                //            print(dict)
                self.close()
            }
        }
        
    }
    
    
    
    @objc private func selectPicture() {
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 更新约束
            self.pictrueSelector.view.snp_updateConstraints { (make) -> Void in
                make.height.equalTo(screenHeight / 3 * 2)
            }
            self.view.layoutIfNeeded()
        }
    }
    
    
    // 懒加载textView视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
//        tv.text = "输入新鲜事..."
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.lightGrayColor()
        tv.backgroundColor = UIColor.greenColor()
        // 开启上下滚动
        tv.alwaysBounceVertical = true
        // keyboardDismissMode 这个属性起作用的前提是滚动视图可以滚动
        tv.keyboardDismissMode = .OnDrag
        
        // 设置textView的代理
        tv.delegate = self
        
        return tv
    }()
    
    
    // 占位文本
    private lazy var placeHolder:UILabel = UILabel(text: "输入新鲜事...", fontSize: 18, textColor: UIColor(white: 0.7, alpha: 1))
    // 底部工具条
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    // 图片选择器的控制器
    private lazy var pictrueSelector: PictureSelectorViewController = PictureSelectorViewController()
    
}


// MARK: - UI设置相关的分类
extension ComposeViewController {
    // 设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        
        // 初始的时候设置发送按钮不能交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 自定义导航条 titleView
        let weiboTitle = UILabel(text: "发布微博", fontSize: 18, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(text: AccountViewModel.sharedAccountViewModel.userName ?? "", fontSize: 13, textColor: UIColor.lightGrayColor())
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        
        navigationItem.titleView = titleView
        titleView.addSubview(weiboTitle)
        titleView.addSubview(nameLabel)
        
        // 设置约束
        weiboTitle.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(weiboTitle.snp_bottom)
        }
        
    }

    
    
    // 设置textView文本视图
    private func setTextView() {
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(screenHeight/3)
        }
        
        // 添加占位文本
        textView.addSubview(placeHolder)
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    
    // 设置图片选择器视图
    private func setPictrueSelector() {
        self.addChildViewController(pictrueSelector)
        self.view.addSubview(pictrueSelector.view)
        // 将toolBar移动到最顶层
        self.view.bringSubviewToFront(toolBar)
        
        pictrueSelector.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.bottom.equalTo(self.view.snp_bottom)
            make.height.equalTo(0)
        }
    }
    
    
    // 设置底部工具条
    private func setBottomToolBar() {
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            // toolBar有默认高度，默认是44
            make.height.equalTo(44)
        }
        
        // 设置toolBar的内部按钮
        var items = [UIBarButtonItem]()
        //配置类型字典
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        
        for item in itemSettings {
            // 实例化UIBarButtonItem对象，默认的渲染色是蓝色，并且不能够设置高亮状态的图片
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, imageName: imageName!)
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            let barItem = UIBarButtonItem(customView: btn)
            // 将对象添加到数组中
            items.append(barItem)
            
            // 添加弹簧的item
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        // 移除最后一个
        items.removeLast()
        
        // 设置工具条的按钮数组对象
        toolBar.items = items
        
    }

    
}

extension ComposeViewController:UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        // 如果用户输入了文本，点亮按钮，隐藏占位文本
        // 用户没有输入任何文本，恢复到默认状态
        placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}








